const eventCisternMap = new Map();
export function useEmit(namespace = "ns") {
  let cistern = eventCisternMap.get(namespace);
  if (!cistern) eventCisternMap.set(namespace, (cistern = new Map()));
  function on(type, listener, once) {
    let listenerCistern = cistern.get(type);
    if (!listenerCistern) cistern.set(type, (listenerCistern = []));
    listenerCistern.push({ listener, once });
  }
  function once(type, listener) {
    on(type, listener, true);
  }
  function off(type, listener) {
    const listenerCistern = cistern.get(type);
    if (listenerCistern) {
      for (let i = listenerCistern.length; i--; ) {
        if (listenerCistern[i].listener === listener) {
          listenerCistern.splice(i, 1);
        }
      }
    }
  }
  function emit(type, ...args) {
    const listenerCistern = cistern.get(type);
    if (listenerCistern) {
      for (let i = 0; i < listenerCistern.length; ) {
        const { once, listener } = listenerCistern[i];
        listener(...args);
        if (once) {
          listenerCistern.splice(i, 1);
        } else {
          i++;
        }
      }
    }
  }
  return { on, once, off, emit };
}